<template>
  <div id="app" class="app-container">
    <!-- 全局进度条 -->
    <div v-if="loading" class="global-loading">
      <el-progress 
        :percentage="loadingProgress" 
        :show-text="false"
        :stroke-width="3"
        color="#409EFF"
      />
    </div>

    <!-- 主要内容区域 -->
    <router-view v-slot="{ Component, route }">
      <transition
        :name="route.meta.transition || 'fade'"
        mode="out-in"
        appear
      >
        <keep-alive :include="keepAliveComponents">
          <component :is="Component" :key="route.fullPath" />
        </keep-alive>
      </transition>
    </router-view>

    <!-- 全局消息提示 -->
    <GlobalMessage />
    
    <!-- 全局确认对话框 -->
    <GlobalConfirm />
    
    <!-- 全局图片预览 -->
    <GlobalImageViewer />
    
    <!-- 全局视频播放器 -->
    <GlobalVideoPlayer
      v-if="videoPlayerVisible"
      :src="videoPlayerOptions.src"
      :poster="videoPlayerOptions.poster"
      :autoplay="videoPlayerOptions.autoplay"
      :loop="videoPlayerOptions.loop"
      :muted="videoPlayerOptions.muted"
      @play="handleVideoPlay"
      @pause="handleVideoPause"
      @ended="handleVideoEnded"
      @close="hideVideoPlayer"
    />
    
    <!-- 返回顶部按钮 -->
    <BackToTop />
    
    <!-- 在线客服 -->
    <OnlineService v-if="showOnlineService" />
    
    <!-- 全局快捷键提示 -->
    <ShortcutHelper v-if="showShortcutHelper" @close="showShortcutHelper = false" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useAppStore } from '@/stores/app'
import { useUserStore } from '@/stores/user'
import { useThemeStore } from '@/stores/theme'

// 全局组件
import GlobalMessage from '@/components/global/GlobalMessage.vue'
import GlobalConfirm from '@/components/global/GlobalConfirm.vue'
import GlobalImageViewer from '@/components/global/GlobalImageViewer.vue'
import GlobalVideoPlayer from '@/components/global/GlobalVideoPlayer.vue'
import BackToTop from '@/components/common/BackToTop.vue'
import OnlineService from '@/components/common/OnlineService.vue'
import ShortcutHelper from '@/components/common/ShortcutHelper.vue'

const router = useRouter()
const route = useRoute()
const appStore = useAppStore()
const userStore = useUserStore()
const themeStore = useThemeStore()

// 响应式数据
const loading = ref(false)
const loadingProgress = ref(0)
const showOnlineService = ref(true)
const showShortcutHelper = ref(false)

// 需要缓存的组件
const keepAliveComponents = computed(() => {
  return [
    'Dashboard',
    'CourseList',
    'ExamList',
    'TaskList',
    'NewsList',
    'LibraryList',
    'MallList',
    'NoteList',
    'DocumentList'
  ]
})

// 视频播放器状态
const videoPlayerVisible = ref(false)
const videoPlayerOptions = ref({
  src: '',
  poster: '',
  autoplay: true,
  loop: false,
  muted: false
})

// 视频播放器控制方法
const showVideoPlayer = (options) => {
  videoPlayerOptions.value = { ...videoPlayerOptions.value, ...options }
  videoPlayerVisible.value = true
}

const hideVideoPlayer = () => {
  videoPlayerVisible.value = false
}

const handleVideoPlay = () => {
  console.log('视频开始播放')
}

const handleVideoPause = () => {
  console.log('视频暂停')
}

const handleVideoEnded = () => {
  hideVideoPlayer()
}

// 将视频播放控制暴露给全局
appStore.$patch({
  showVideoPlayer,
  hideVideoPlayer
})

// 监听路由变化
watch(route, (to, from) => {
  // 页面切换时的逻辑
  if (to.meta.requiresAuth && !userStore.isLoggedIn) {
    router.push('/login')
    return
  }
  
  // 更新页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - ZenithMind教育平台`
  }
  
  // 页面访问统计
  appStore.recordPageVisit(to.path)
})

// 全局快捷键
const handleKeydown = (event) => {
  // Ctrl/Cmd + K 打开搜索
  if ((event.ctrlKey || event.metaKey) && event.key === 'k') {
    event.preventDefault()
    appStore.toggleGlobalSearch()
  }
  
  // Ctrl/Cmd + / 显示快捷键帮助
  if ((event.ctrlKey || event.metaKey) && event.key === '/') {
    event.preventDefault()
    showShortcutHelper.value = true
  }
  
  // ESC 关闭模态框
  if (event.key === 'Escape') {
    appStore.closeAllModals()
  }
}

// 全局错误处理
const handleGlobalError = (error) => {
  console.error('全局错误:', error)
  ElMessage.error('系统出现错误，请稍后重试')
}

// 网络状态监听
const handleOnline = () => {
  ElMessage.success('网络连接已恢复')
  appStore.setNetworkStatus(true)
}

const handleOffline = () => {
  ElMessage.warning('网络连接已断开')
  appStore.setNetworkStatus(false)
}

// 页面可见性变化
const handleVisibilityChange = () => {
  if (document.hidden) {
    appStore.setPageVisible(false)
  } else {
    appStore.setPageVisible(true)
    // 页面重新可见时刷新数据
    appStore.refreshCurrentPageData()
  }
}

onMounted(async () => {
  // 初始化应用
  try {
    loading.value = true
    loadingProgress.value = 20
    
    // 初始化主题
    await themeStore.initTheme()
    loadingProgress.value = 40
    
    // 初始化用户信息
    await userStore.initUser()
    loadingProgress.value = 60
    
    // 初始化应用配置
    await appStore.initApp()
    loadingProgress.value = 80
    
    // 注册全局事件监听
    document.addEventListener('keydown', handleKeydown)
    window.addEventListener('error', handleGlobalError)
    window.addEventListener('online', handleOnline)
    window.addEventListener('offline', handleOffline)
    document.addEventListener('visibilitychange', handleVisibilityChange)
    
    loadingProgress.value = 100
    
    setTimeout(() => {
      loading.value = false
    }, 500)
    
  } catch (error) {
    console.error('应用初始化失败:', error)
    loading.value = false
    ElMessage.error('应用初始化失败，请刷新页面重试')
  }
})

onUnmounted(() => {
  // 清理事件监听
  document.removeEventListener('keydown', handleKeydown)
  window.removeEventListener('error', handleGlobalError)
  window.removeEventListener('online', handleOnline)
  window.removeEventListener('offline', handleOffline)
  document.removeEventListener('visibilitychange', handleVisibilityChange)
})
</script>

<style lang="scss" scoped>
.app-container {
  height: 100vh;
  overflow-x: hidden;
}

.global-loading {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 9999;
}

// 页面切换动画
.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
}

.slide-left-enter-active,
.slide-left-leave-active {
  transition: transform 0.3s ease;
}

.slide-left-enter-from {
  transform: translateX(100%);
}

.slide-left-leave-to {
  transform: translateX(-100%);
}

.slide-right-enter-active,
.slide-right-leave-active {
  transition: transform 0.3s ease;
}

.slide-right-enter-from {
  transform: translateX(-100%);
}

.slide-right-leave-to {
  transform: translateX(100%);
}

.zoom-enter-active,
.zoom-leave-active {
  transition: transform 0.3s ease, opacity 0.3s ease;
}

.zoom-enter-from,
.zoom-leave-to {
  transform: scale(0.9);
  opacity: 0;
}
</style>
